package cn.xique.module.token.web;



import com.jfinal.kit.Ret;
import io.jboot.web.controller.JbootController;
import io.jboot.web.controller.annotation.RequestMapping;
import io.jpress.module.token.model.GizwitsToken;
import io.jpress.module.token.service.GizwitsTokenService;
import io.jpress.module.token.service.TokenService;
import net.sf.ehcache.util.TimeUtil;
import org.joda.time.DateTimeUtils;
import org.json.JSONObject;

import javax.inject.Inject;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

@RequestMapping("/GizwitsToken")
public class TokenController extends JbootController {

        @Inject
        private GizwitsTokenService gs;

         @Inject
        private TokenService ts;


        public void index() {
            //从数据库读取tocken，如果没有，或者过期，就访问机智云获取token，（有效期是7天），否则就直接返回token
            GizwitsToken gizwitsToken = gs.findById("token_key");
            if(gizwitsToken == null){
                gizwitsToken = new GizwitsToken();
                String token = ts.GetToKenFormGiz();
                gizwitsToken.setValue(token);
                gizwitsToken.setGenarateTime(new Date());
                gizwitsToken.setToken("token_key");
                gizwitsToken.save();

            }else{//判断是否已经到期
                // 取当前日期：
                Date today = new Date();
                Date mDate = gizwitsToken.getGenarateTime();
               int days = (int) ((today.getTime() - mDate.getTime())/(24*3600*1000));
                if(days > 6){//需要刷新token了
                    String token = ts.GetToKenFormGiz();
                    gizwitsToken.setValue(token);
                    gizwitsToken.setGenarateTime(today);
                    gizwitsToken.update();

                }


            }
            renderJson(Ret.ok().set("success", true).set("token", gizwitsToken.getValue()));
        }
}
